(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.invCreate.createContinueController', createContinueController);
	createContinueController.$inject = [ '$q', '$filter', '$scope', 'Constants', 'formatService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'invoiceCreateService', 'dateService', 'arithService', 'commonService'];
	function createContinueController($q, $filter, $scope, Constants, formatService, modalService, gridService, layoutConfig, validatorConfig, authService, invoiceCreateService, dateService, arithService, commonService) {
		var ctrl = this, piInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.invLoad = {};
		ctrl.invLoad.pi = {};
		
		ctrl.init = function() {
			ctrl.invoiceTypeChanged = function(rowObj, form) {
				if (rowObj.invoiceType) {
					// reset paycodeOptions.data
					if (rowObj._refTypeConfig && rowObj._refTypeConfig.options){
						angular.forEach(ctrl.invoiceTypeOptions, function(invoiceType, index) {
							if(rowObj.invoiceType == invoiceType.value){
								rowObj._refTypeConfig.options = invoiceType.extProperty.refTypeOptions;
								rowObj.calSymbol = invoiceType.extProperty.calSymbol;
								rowObj.isAdjAmtShow = invoiceType.extProperty.isAdjAmtShow;
								rowObj.isAdjCodeShow = invoiceType.extProperty.isAdjCodeShow;
								rowObj.isDiscAmtShow = invoiceType.extProperty.isDiscAmtShow;
								rowObj.isGrossAmtShow = invoiceType.extProperty.isGrossAmtShow;
							}
						});
						ctrl.changeGrossAmt(rowObj);
					}
				}
			};
			invoiceCreateService.getCalendarCodes().then(function(response) {
				ctrl.calendarCodes = response.data;
			});
			invoiceCreateService.getCommunityCodeQOptions().then(function(communityQRes) {
				ctrl.communityCodeQOptions = communityQRes.data;
			});
			invoiceCreateService.getCurrencyOptions().then(function(response) {
				ctrl.currencyOptions = response.data;
			});
			if(ctrl.validatorConfig && ctrl.validatorConfig.pi && ctrl.validatorConfig.pi.invoiceList){
				//add validator
				if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.invoicesCfg.tableConfigs.table.validatorConfig = ctrl.validatorConfig.pi.invoiceList;
			}
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.invoicesCfg.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.invLoad.pi.invoiceList';
			authService.createContinue(piInfo).then(function(response) {
				ctrl.changePiAmt = function(value){
					if(!isAmtValid(value)){
						return;
					}
					ctrl.invLoad.piTotalAmt = 0;
					angular.forEach(ctrl.invLoad.pi.invoiceList, function(invoice, index) {
						invoice.invoiceAmt = arithService.sub(invoice.invoiceGrossAmt, invoice.invoiceAdjustAmt, invoice.invoiceDiscAmt);
						ctrl.invLoad.piTotalAmt = arithService.calc(ctrl.invLoad.piTotalAmt, invoice.invoiceAmt, invoice.calSymbol);
					});
				};
				ctrl.changeGrossAmt = function(value){
					if(!isAmtValid(value)){
						return;
					}
					ctrl.invLoad.piTotalAmt = 0;
					angular.forEach(ctrl.invLoad.pi.invoiceList, function(invoice, index) {
						invoice.invoiceGrossAmt = arithService.add(invoice.invoiceAmt, invoice.invoiceAdjustAmt, invoice.invoiceDiscAmt);
						ctrl.invLoad.piTotalAmt = arithService.calc(ctrl.invLoad.piTotalAmt, invoice.invoiceAmt, invoice.calSymbol);
					});
				};
				ctrl.calInvoiceTenor = function(){
					angular.forEach(ctrl.invLoad.pi.invoiceList, function(invoice, index) {
						if(invoice.invoiceDate && invoice.invoiceMaturitydate){
							invoice.invoiceTenor = dateService.compareDate(invoice.invoiceDate, invoice.invoiceMaturitydate);
						}
					});
				};
				ctrl.setMaturitydate = function(value, formCtrl, isInitialized){
					if(!isInitialized){
						var piLoad = angular.copy(ctrl.invLoad);
						piLoad.partyType = "BUYER";
						piLoad.operation = 'I';
						piLoad.pi.invoiceList[0] = value;
						if(piLoad.pi.communityCode != null && piLoad.pi.sellerCode != null && value.invoiceMaturitydateOrg != null){
							invoiceCreateService.getMaturitydate(piLoad).then(function(response){
								value.invoiceMaturitydate = response.data.pi.invoiceList[0].invoiceMaturitydate;
							});
						}else if(value.invoiceMaturitydateOrg != null){
							value.invoiceMaturitydate = value.invoiceMaturitydateOrg;
						}
					}
				};
				if (response.data && response.data.model && response.data.task) {
					var invLoad = response.data.model;
					invLoad.partyType = "BUYER";
					var task = response.data.task;
					invoiceCreateService.invoiceTypeOptions(invLoad).then(function(response){
						ctrl.invoiceTypeOptions = response.data;
						ctrl.invLoad = invLoad;
						ctrl.invLoad.pi.invoiceList = ctrl.invLoad.pi.invoiceList || [];
						ctrl.invLoad.pi.invoiceDeleteList = ctrl.invLoad.pi.invoiceDeleteList || [];
						ctrl.invLoad.taskId = task.taskId;
						ctrl.resetInvoiceListByData();
					});
				};
			});
		};
		
		ctrl.resetInvoiceListByData = function(isView) {
			angular.forEach(ctrl.invLoad.pi.invoiceList, function(invoice, index) {
				invoice._refTypeConfig = {
						model : "refType",
						type : "select",
						options : {},
						uppercase : true
				};
				if (isView) invoice._refTypeConfig.readonly = true;
			});
		};
		
		function isAmtValid(value){
			if(value){
				value.invoiceAmt = (value.invoiceAmt == undefined || value.invoiceAmt.length == 0) ? "0" : value.invoiceAmt;
				value.invoiceGrossAmt = (value.invoiceGrossAmt == undefined || value.invoiceGrossAmt.length == 0) ? "0" : value.invoiceGrossAmt;
				value.invoiceAdjustAmt = (value.invoiceAdjustAmt == undefined || value.invoiceAdjustAmt.length == 0) ? "0" : value.invoiceAdjustAmt;
				value.invoiceDiscAmt = (value.invoiceDiscAmt == undefined || value.invoiceDiscAmt.length == 0) ? "0" : value.invoiceDiscAmt;
				var pattern = /^(-?\d+)(\.\d+)?$/;
				if(pattern.test(value.invoiceAmt)
				&& pattern.test(value.invoiceGrossAmt)
				&& pattern.test(value.invoiceAdjustAmt)
				&& pattern.test(value.invoiceDiscAmt)){
					return true;
				}
				return false;
			}
		};

		ctrl.createContinueSave = function() {
			return authService.createContinueSave(ctrl.invLoad).then(saveSuccessful, saveFailed);
		};

		ctrl.createContinueSubmit = function() {
			return authService.createContinueSubmit(ctrl.invLoad).then(submitSuccessful, submitFailed);
		};
		
		ctrl.createContinueCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.invLoad.pi.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.createContinueCancel(ctrl.invLoad).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('apf.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'apf.workflow.wfTxn.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.inv.create',
					'state' : 'apf.invCreate.create',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				angular.extend(ctrl.invLoad, response.data.model);
			}else if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('apf.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'apf.workflow.wfTxn.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.inv.create',
					'state' : 'apf.invCreate.create',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}	
		
		ctrl.addPi = function(row) {
			return $q(function(resolved, rejected) {
				var messages = [];
				if(!ctrl.invLoad.pi.communityCode){
					messages.push('label.communitycode.required');
				}
				if(!ctrl.invLoad.pi.sellerCode){
					messages.push('label.selelrcode.required');
				}
				if(messages.length > 0){
					modalService.openErrorDialogs({
						messages : messages
					});
					return false;
				}
				row.invoiceDate = ctrl.invLoad.pi.piDate;
				row.invoiceType = 'I';
				row.invoiceAmt = 0;
				row.invoiceGrossAmt = 0;
				row.invoiceAdjustAmt = 0;
				row.invoiceDiscAmt = 0;
				row.calSymbol = "+";
				row.isAdjAmtShow = true;
				row.isAdjCodeShow = true;
				row.isDiscAmtShow = true;
				row.isGrossAmtShow = true;
				row.dataStatus = 'C';
				row._refTypeConfig = {
				     model : "refType",
				     type : "select",
				     options : {},
				     uppercase : true
				};
				if(!ctrl.invLoad.numPiTotal){
					ctrl.invLoad.numPiTotal = 0;
				}
				ctrl.invLoad.numPiTotal = ctrl.invLoad.numPiTotal + 1;
				resolved();
			});
		};
		
		$scope.$on('REMOVE_ROWS', function(event, selectedRows) {
			angular.forEach(selectedRows, function(inv, index) {
				if(inv.entity.invoiceId){
					ctrl.invLoad.pi.invoiceDeleteList.push(inv.entity);
				}
				ctrl.invLoad.numPiTotal = ctrl.invLoad.numPiTotal - 1;
				ctrl.changePiAmt(inv.entity);
			});
		});
		
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedInvoices = selectedRows;
		}
		
	}
})(angular);
